package com.hubiwei.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hubiwei.gmall.realtime.app.BaseAppV2;
import com.hubiwei.gmall.realtime.bean.OrderWide;
import com.hubiwei.gmall.realtime.bean.PaymentWide;
import com.hubiwei.gmall.realtime.bean.ProductStats;
import com.hubiwei.gmall.realtime.common.Constant;
import com.hubiwei.gmall.realtime.function.DimAsyncFunction;
import com.hubiwei.gmall.realtime.util.AtguiguUtil;
import com.hubiwei.gmall.realtime.util.DimUtil;
import com.hubiwei.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/3 9:25
 */
public class DwsProductApp extends BaseAppV2 {
    public static void main(String[] args) {
        new DwsProductApp().init(
            4002, 1, "DwsProductApp", "DwsProductApp",
            Constant.TOPIC_DWD_PAGE, Constant.TOPIC_DWD_DISPLAY,
            Constant.TOPIC_DWD_FAVOR_INFO, Constant.TOPIC_DWD_CART_INFO,
            Constant.TOPIC_DWM_ORDER_WIDE, Constant.TOPIC_DWM_PAYMENT_WIDE,
            Constant.TOPIC_DWD_REFUND_PAYMENT, Constant.TOPIC_DWD_COMMENT_INFO
        );
    }
    
    @Override
    public void run(StreamExecutionEnvironment env,
                    HashMap<String, DataStreamSource<String>> topicAndStreamMap) {
        // 1. 解析8个流, 合并为一个
        DataStream<ProductStats> psStream = parseStreamsAndUnionOne(topicAndStreamMap);
        // 2. 开窗聚合
        SingleOutputStreamOperator<ProductStats> aggregatedStream = aggregate(psStream);
        // 3. join 维度信息
        SingleOutputStreamOperator<ProductStats> psStreamWithDim = joinDims(aggregatedStream);
        // 4. 写入到clickhouse中
        writeToClickHouse(psStreamWithDim);
        
        // 5. 为了dws层的商品行为关键词的使用, 需要把数据再写一份到kafka中
        writeToKafka(psStreamWithDim);
        
    }
    
    private void writeToKafka(SingleOutputStreamOperator<ProductStats> psStreamWithDim) {
        psStreamWithDim
            .map(JSON::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWS_PRODUCT_STATS)).name("kafka");
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<ProductStats> stream) {
//        stream.print();
        stream
            .addSink(FlinkSinkUtil.getClickHouseSink("gmall2021", "product_stats_2021", ProductStats.class)).name("clickhouse");
        
    }
    
    private SingleOutputStreamOperator<ProductStats> joinDims(SingleOutputStreamOperator<ProductStats> aggregatedStream) {
        return AsyncDataStream.unorderedWait(
            aggregatedStream,
            new DimAsyncFunction<ProductStats>() {
                @Override
                protected void addDim(Connection phoenixConnection,
                                      Jedis redisClient,
                                      ProductStats ps,
                                      ResultFuture<ProductStats> resultFuture) {
                    JSONObject skuInfo = DimUtil.getDim(phoenixConnection,
                                                        redisClient,
                                                        "dim_sku_info",
                                                        ps.getSku_id());
                    ps.setSku_name(skuInfo.getString("SKU_NAME"));
                    ps.setSku_price(skuInfo.getBigDecimal("PRICE")); // 价格
                    
                    ps.setSpu_id(skuInfo.getLong("SPU_ID"));
                    ps.setTm_id(skuInfo.getLong("TM_ID"));
                    ps.setCategory3_id(skuInfo.getLong("CATEGORY3_ID"));
                    
                    // 4. spu
                    JSONObject spuInfo = DimUtil.getDim(phoenixConnection,
                                                        redisClient,
                                                        "dim_spu_info",
                                                        ps.getSpu_id());
                    ps.setSpu_name(spuInfo.getString("SPU_NAME"));
                    
                    // 5. tm
                    JSONObject tmInfo = DimUtil.getDim(phoenixConnection,
                                                       redisClient,
                                                       "dim_base_trademark",
                                                       ps.getTm_id());
                    ps.setTm_name(tmInfo.getString("TM_NAME"));
                    
                    // 5. tm
                    JSONObject c3Info = DimUtil.getDim(phoenixConnection,
                                                       redisClient,
                                                       "dim_base_category3",
                                                       ps.getCategory3_id());
                    ps.setCategory3_name(c3Info.getString("NAME"));
                    
                    resultFuture.complete(Collections.singletonList(ps));
                }
            },
            60,
            TimeUnit.SECONDS
        );
    }
    
    private SingleOutputStreamOperator<ProductStats> aggregate(DataStream<ProductStats> psStream) {
        return psStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<ProductStats>forBoundedOutOfOrderness(Duration.ofSeconds(20))
                    .withTimestampAssigner((ps, ts) -> ps.getTs())
            )
            .keyBy(ProductStats::getSku_id)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<ProductStats>() {
                    @Override
                    public ProductStats reduce(ProductStats ps1,
                                               ProductStats ps2) throws Exception {
                        
                        ps1.setClick_ct(ps1.getClick_ct() + ps2.getClick_ct());
                        ps1.setDisplay_ct(ps1.getDisplay_ct() + ps2.getDisplay_ct());
                        ps1.setFavor_ct(ps1.getFavor_ct() + ps2.getFavor_ct());
                        ps1.setCart_ct(ps1.getCart_ct() + ps2.getCart_ct());
                        ps1.setComment_ct(ps1.getComment_ct() + ps2.getComment_ct());
                        ps1.setGood_comment_ct(ps1.getGood_comment_ct() + ps2.getGood_comment_ct());
                        
                        ps1.setOrder_sku_num(ps1.getOrder_sku_num() + ps2.getOrder_sku_num());
                        
                        ps1.setOrder_amount(ps1.getOrder_amount().add(ps2.getOrder_amount()));
                        ps1.setPayment_amount(ps1.getPayment_amount().add(ps2.getPayment_amount()));
                        ps1.setRefund_amount(ps1.getRefund_amount().add(ps2.getRefund_amount()));
                        
                        ps1.getOrderIdSet().addAll(ps2.getOrderIdSet());
                        ps1.getPaidOrderIdSet().addAll(ps2.getPaidOrderIdSet());
                        ps1.getRefundOrderIdSet().addAll(ps2.getRefundOrderIdSet());
                        
                        return ps1;
                    }
                },
                new ProcessWindowFunction<ProductStats, ProductStats, Long, TimeWindow>() {
                    @Override
                    public void process(Long key,
                                        Context ctx,
                                        Iterable<ProductStats> elements,
                                        Collector<ProductStats> out) throws Exception {
                        ProductStats ps = elements.iterator().next();
                        
                        ps.setStt(AtguiguUtil.toDateString(ctx.window().getStart(), "yyyy-MM-dd HH:mm:ss"));
                        ps.setEdt(AtguiguUtil.toDateString(ctx.window().getEnd(), "yyyy-MM-dd HH:mm:ss"));
                        ps.setTs(System.currentTimeMillis());
                        
                        ps.setOrder_ct((long) ps.getOrderIdSet().size());
                        ps.setPaid_order_ct((long) ps.getPaidOrderIdSet().size());
                        ps.setRefund_order_ct((long) ps.getRefundOrderIdSet().size());
                        
                        out.collect(ps);
                    }
                }
            );
        
    }
    
    private DataStream<ProductStats> parseStreamsAndUnionOne(HashMap<String, DataStreamSource<String>> topicAndStreamMap) {
        // 1. 点击
        SingleOutputStreamOperator<ProductStats> clickStream = topicAndStreamMap
            .get(Constant.TOPIC_DWD_PAGE)
            .flatMap(new FlatMapFunction<String, ProductStats>() {
                @Override
                public void flatMap(String value,
                                    Collector<ProductStats> out) throws Exception {
                    
                    JSONObject obj = JSON.parseObject(value);
                    JSONObject page = obj.getJSONObject("page");
                    
                    String page_id = page.getString("page_id");
                    String item_type = page.getString("item_type");
                    
                    if ("good_detail".equals(page_id) && "sku_id".equals(item_type)) {
                        Long skuId = page.getLong("item");
                        
                        ProductStats ps = new ProductStats();
                        ps.setSku_id(skuId);
                        ps.setClick_ct(1L);
                        ps.setTs(obj.getLong("ts"));
                        out.collect(ps);
                        
                    }
                    
                }
            });
        
        // 2. 曝光
        SingleOutputStreamOperator<ProductStats> displayStream = topicAndStreamMap
            .get(Constant.TOPIC_DWD_DISPLAY)
            .filter(value -> {
                JSONObject obj = JSON.parseObject(value);
                // 把item_type是sku_id的数据留下
                String itemType = obj.getString("item_type");
                return "sku_id".equals(itemType);
                
            })
            .map(value -> {
                JSONObject obj = JSON.parseObject(value);
                ProductStats ps = new ProductStats();
                ps.setSku_id(obj.getLong("item"));
                ps.setDisplay_ct(1L);
                ps.setTs(obj.getLong("ts"));
                return ps;
            });
        
        // 3. 收藏
        SingleOutputStreamOperator<ProductStats> favorStream = topicAndStreamMap
            .get(Constant.TOPIC_DWD_FAVOR_INFO)
            
            .map(value -> {
                JSONObject obj = JSON.parseObject(value);
                ProductStats ps = new ProductStats();
                ps.setSku_id(obj.getLong("sku_id"));
                ps.setFavor_ct(1L);
                ps.setTs(AtguiguUtil.toTs(obj.getString("create_time")));
                return ps;
            });
        
        // 4. 购物车
        SingleOutputStreamOperator<ProductStats> cartStream = topicAndStreamMap
            .get(Constant.TOPIC_DWD_CART_INFO)
            
            .map(value -> {
                JSONObject obj = JSON.parseObject(value);
                ProductStats ps = new ProductStats();
                ps.setSku_id(obj.getLong("sku_id"));
                ps.setCart_ct(1L);
                ps.setTs(AtguiguUtil.toTs(obj.getString("create_time")));
                return ps;
            });
        
        // 5. 订单
        SingleOutputStreamOperator<ProductStats> orderStream = topicAndStreamMap
            .get(Constant.TOPIC_DWM_ORDER_WIDE)
            .map(json -> {
                OrderWide orderWide = JSON.parseObject(json, OrderWide.class);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(orderWide.getSku_id());
                ps.getOrderIdSet().add(orderWide.getOrder_id());  // 这个集合只用一个, 获取之后直接向集合中添加id
                
                ps.setOrder_amount(orderWide.getSplit_total_amount()); // 使用商品的分摊金额
                ps.setOrder_sku_num(orderWide.getSku_num());
                
                ps.setTs(AtguiguUtil.toTs(orderWide.getCreate_time()));
                
                return ps;
                
            });
        
        // 6. 支付
        SingleOutputStreamOperator<ProductStats> paymentStream = topicAndStreamMap
            .get(Constant.TOPIC_DWM_PAYMENT_WIDE)
            .map(json -> {
                PaymentWide paymentWide = JSON.parseObject(json, PaymentWide.class);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(paymentWide.getSku_id());
                ps.setPayment_amount(paymentWide.getSplit_total_amount());
                
                ps.getPaidOrderIdSet().add(paymentWide.getOrder_id());
                
                ps.setTs(AtguiguUtil.toTs(paymentWide.getPayment_create_time()));
                
                return ps;
                
            });
        
        // 7. 退款
        SingleOutputStreamOperator<ProductStats> refundStream = topicAndStreamMap
            .get(Constant.TOPIC_DWD_REFUND_PAYMENT)
            
            .map(value -> {
                JSONObject obj = JSON.parseObject(value);
                ProductStats ps = new ProductStats();
                ps.setSku_id(obj.getLong("sku_id"));
                ps.setRefund_amount(obj.getBigDecimal("total_amount"));
                ps.getRefundOrderIdSet().add(obj.getLong("order_id"));
                ps.setTs(AtguiguUtil.toTs(obj.getString("create_time")));
                return ps;
            });
        
        // 8. 评价
        SingleOutputStreamOperator<ProductStats> commentStream = topicAndStreamMap
            .get(Constant.TOPIC_DWD_COMMENT_INFO)
            
            .map(value -> {
                JSONObject obj = JSON.parseObject(value);
                ProductStats ps = new ProductStats();
                ps.setSku_id(obj.getLong("sku_id"));
                
                ps.setComment_ct(1L);
                
                String appraise = obj.getString("appraise");
                if (Constant.FIVE_STAR_COMMENT.equals(appraise) || Constant.FOUR_STAR_COMMENT.equals(appraise)) {
                    ps.setGood_comment_ct(1L);
                }
                
                ps.setTs(AtguiguUtil.toTs(obj.getString("create_time")));
                return ps;
            });
        
        return clickStream.union(displayStream,
                                 favorStream,
                                 cartStream,
                                 orderStream,
                                 paymentStream,
                                 refundStream,
                                 commentStream
        );
        
    }
}
